package com.wgh.cart.controller;

import com.wgh.cart.dto.CartDTO;
import com.wgh.cart.entity.CartItem;
import com.wgh.cart.service.CartService;
import com.wgh.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 购物车控制器
 * 提供购物车相关的RESTful API
 */
@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     */
    @PostMapping
    public Result<Boolean> addToCart(
            @RequestParam Long userId,
            @RequestParam Long productId,
            @RequestParam Long skuId,
            @RequestParam Integer quantity,
            @RequestParam(required = false) String attributes) {
        try {
            return cartService.addToCart(userId, productId, skuId, quantity, attributes);
        } catch (Exception e) {
            return Result.error("添加商品到购物车失败：" + e.getMessage());
        }
    }

    /**
     * 更新购物车商品数量
     */
    @PutMapping("/item/{cartItemId}/quantity")
    public Result<Boolean> updateCartItemQuantity(
            @RequestParam Long userId,
            @PathVariable Long cartItemId,
            @RequestParam Integer quantity) {
        try {
            return cartService.updateCartItemQuantity(userId, cartItemId, quantity);
        } catch (Exception e) {
            return Result.error("更新购物车商品数量失败：" + e.getMessage());
        }
    }

    /**
     * 更新购物车商品选中状态
     */
    @PutMapping("/item/{cartItemId}/selected")
    public Result<Boolean> updateCartItemSelected(
            @RequestParam Long userId,
            @PathVariable Long cartItemId,
            @RequestParam Boolean selected) {
        try {
            return cartService.updateCartItemSelected(userId, cartItemId, selected);
        } catch (Exception e) {
            return Result.error("更新购物车商品选中状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新购物车商品选中状态
     */
    @PutMapping("/items/selected")
    public Result<Boolean> updateCartItemsSelected(
            @RequestParam Long userId,
            @RequestParam Boolean selected) {
        try {
            return cartService.updateCartItemsSelected(userId, selected);
        } catch (Exception e) {
            return Result.error("批量更新购物车商品选中状态失败：" + e.getMessage());
        }
    }

    /**
     * 从购物车中删除商品
     */
    @DeleteMapping("/item/{cartItemId}")
    public Result<Boolean> removeFromCart(
            @RequestParam Long userId,
            @PathVariable Long cartItemId) {
        try {
            return cartService.removeFromCart(userId, cartItemId);
        } catch (Exception e) {
            return Result.error("从购物车中删除商品失败：" + e.getMessage());
        }
    }

    /**
     * 清空购物车
     */
    @DeleteMapping
    public Result<Boolean> clearCart(@RequestParam Long userId) {
        try {
            return cartService.clearCart(userId);
        } catch (Exception e) {
            return Result.error("清空购物车失败：" + e.getMessage());
        }
    }

    /**
     * 获取购物车列表
     */
    @GetMapping
    public Result<List<CartDTO>> getCartList(@RequestParam Long userId) {
        try {
            Result<List<CartItem>> result = cartService.getCartList(userId);
            if (result.isSuccess()) {
                List<CartDTO> cartDTOs = convertToDTOList(result.getData());
                return Result.success(cartDTOs);
            } else {
                return Result.error(result.getMessage());
            }
        } catch (Exception e) {
            return Result.error("获取购物车列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取购物车中选中的商品
     */
    @GetMapping("/selected")
    public Result<List<CartDTO>> getSelectedCartItems(@RequestParam Long userId) {
        try {
            Result<List<CartItem>> result = cartService.getSelectedCartItems(userId);
            if (result.isSuccess()) {
                List<CartDTO> cartDTOs = convertToDTOList(result.getData());
                return Result.success(cartDTOs);
            } else {
                return Result.error(result.getMessage());
            }
        } catch (Exception e) {
            return Result.error("获取购物车中选中的商品失败：" + e.getMessage());
        }
    }

    /**
     * 获取购物车商品数量
     */
    @GetMapping("/count")
    public Result<Integer> getCartItemCount(@RequestParam Long userId) {
        try {
            return cartService.getCartItemCount(userId);
        } catch (Exception e) {
            return Result.error("获取购物车商品数量失败：" + e.getMessage());
        }
    }

    /**
     * 将CartItem列表转换为CartDTO列表
     */
    private List<CartDTO> convertToDTOList(List<CartItem> cartItems) {
        if (cartItems == null || cartItems.isEmpty()) {
            return new ArrayList<>();
        }
        List<CartDTO> cartDTOs = new ArrayList<>();
        for (CartItem item : cartItems) {
            CartDTO dto = new CartDTO();
            dto.setId(item.getId());
            dto.setUserId(item.getUserId());
            dto.setProductId(item.getProductId());
            dto.setSkuId(item.getSkuId());
            dto.setProductName(item.getProductName());
            dto.setProductImage(item.getProductImage());
            dto.setPrice(item.getPrice());
            dto.setQuantity(item.getQuantity());
            dto.setAttributes(item.getAttributes());
            dto.setSelected(item.getSelected());
            dto.setCreateTime(item.getCreateTime());
            dto.setUpdateTime(item.getUpdateTime());
            cartDTOs.add(dto);
        }
        return cartDTOs;
    }
}